/*******************************************************************************
 * (c) Copyright 2017 lvxi. All Rights Reserved.
 ******************************************************************************/

package edu.jxufe.nb112.common.security.shiro;

import edu.jxufe.nb112.common.code.security.mode.IUser;
import edu.jxufe.nb112.common.security.service.SecurityService;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.SubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSubjectFactory;
import org.apache.shiro.web.subject.support.WebDelegatingSubject;
import org.springframework.util.StringUtils;

/**
 * Created by lvxi on 2017/2/12.
 */
public class UserSubjectFactory extends DefaultWebSubjectFactory {

    private SecurityService securityService;

    @Override
    public Subject createSubject(SubjectContext subjectContext) {
        Subject subject = super.createSubject(subjectContext);
        if(subject instanceof WebDelegatingSubject){
            String account = (String) subject.getPrincipal();
            if(StringUtils.hasText(account)){
                IUser user = securityService.findUserByAccount(account);
                UserSubject userSubject =new UserSubject((WebDelegatingSubject)subject,subjectContext.isSessionCreationEnabled(),user);
                Session session = subjectContext.getSession();
                if(user!=null && session!=null) {
                    session.setAttribute("userProfile",user);
                    return userSubject;
                }

            }
        }
        return subject;
    }

    public SecurityService getSecurityService() {
        return securityService;
    }

    public void setSecurityService(SecurityService securityService) {
        this.securityService = securityService;
    }
}
